package com.sun.jeecgexam.apache;

import java.io.*;
import java.net.Socket;

/**
 * Created by sun on 2017/4/13.
 */
public class Processor implements  Runnable{
    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    public static final String WEBROOT = "/Users/sun/";
    public Processor(Socket socket){
        this.socket = socket;
        try {
            this.inputStream = this.socket.getInputStream();
            this.outputStream = this.socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理请求
     */
    public void run() {

        String filename = parse(inputStream);

        sendFile(filename);

    }


    public String parse(InputStream inputStream) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String filename = "";

        try {
            // Method Uri Version ,GET /sample/index.jsp 1.1
            String firstLine = reader.readLine();
            String[] arr = firstLine.split(" ");

            if (arr.length != 3) {
                this.sendErrMsg(400, "Client query error");
                return filename;
            }
            String uri = arr[1];
            return uri;

        } catch (IOException e) {
            e.printStackTrace();
        }


        return filename;
    }

    /**
     * 返回错误
     * @param code
     * @param errorMsg
     */
    public void sendErrMsg(int code, String errorMsg) {

        PrintStream ps = new PrintStream(outputStream);
        ps.println("HTTP/1.0 " + code + " " + errorMsg);
        ps.println("content-type: text/html");
        ps.println();

        ps.println("<html><header><title>Error Message</title></header>");
        ps.println("<body><h1>ErrorCode:" + code + ",ErrorMsg:" + errorMsg);
        ps.println("</h1></body></html>");

        ps.flush();
        ps.close();

    }

    /**
     *
     * @param filename
     */
    public void sendFile(String filename) {

        File file = new File(WEBROOT + filename);

        // 404
        if (!file.exists()) {

            sendErrMsg(404,"File Not Found");
            return;
        }

        try {
            InputStream ins = new FileInputStream(file);
            byte[] content = new byte[(int) file.length()];
            ins.read(content);

            PrintStream ps = new PrintStream(outputStream);

            ps.println("HTTP/1.0 200 ok");
            ps.println("conent-length:" + content.length);
            ps.println();
            ps.println(content);
            ps.flush();
            ps.close();

            ins.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
